package com.carrental.integration.controller;

import com.carrental.common.result.Result;
import com.carrental.integration.dto.FileUploadDTO;
import com.carrental.integration.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
@Tag(name = "文件上传接口", description = "提供文件上传、删除和查询功能")
public class FileController {

    private final FileService fileService;

    /**
     * 上传单个文件
     *
     * @param file 文件
     * @return 文件上传响应
     */
    @PostMapping("/upload")
    @Operation(summary = "上传单个文件", description = "上传单个文件到MinIO存储")
    public Result<FileUploadDTO> uploadFile(
            @Parameter(description = "文件", required = true)
            @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failed("上传的文件不能为空");
        }
        try {
            log.info("开始上传文件: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());
            String fileUrl = fileService.uploadFile(file);
            log.info("文件上传成功: {}", fileUrl);
            
            FileUploadDTO uploadDTO = FileUploadDTO.builder()
                    .originalFilename(file.getOriginalFilename())
                    .size(file.getSize())
                    .contentType(file.getContentType())
                    .url(fileUrl)
                    .path(fileUrl.substring(0, fileUrl.indexOf("?") != -1 ? 
                            fileUrl.indexOf("?") : fileUrl.length()))
                    .build();
            
            return Result.success("文件上传成功", uploadDTO);
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return Result.failed("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 批量上传文件
     *
     * @param files 文件列表
     * @return 文件上传响应列表
     */
    @PostMapping("/batch-upload")
    @Operation(summary = "批量上传文件", description = "批量上传多个文件到MinIO存储")
    public Result<List<FileUploadDTO>> uploadFiles(
            @Parameter(description = "文件列表", required = true)
            @RequestParam("files") List<MultipartFile> files) {
        if (files.isEmpty()) {
            return Result.failed("上传的文件不能为空");
        }
        try {
            log.info("开始批量上传文件, 数量: {}", files.size());
            List<String> fileUrls = fileService.uploadFiles(files);
            log.info("批量上传文件成功, 数量: {}", fileUrls.size());
            
            List<FileUploadDTO> uploadDTOs = new ArrayList<>();
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                String fileUrl = fileUrls.get(i);
                
                FileUploadDTO uploadDTO = FileUploadDTO.builder()
                        .originalFilename(file.getOriginalFilename())
                        .size(file.getSize())
                        .contentType(file.getContentType())
                        .url(fileUrl)
                        .path(fileUrl.substring(0, fileUrl.indexOf("?") != -1 ? 
                                fileUrl.indexOf("?") : fileUrl.length()))
                        .build();
                
                uploadDTOs.add(uploadDTO);
            }
            
            return Result.success("文件上传成功", uploadDTOs);
        } catch (Exception e) {
            log.error("批量上传文件失败: {}", e.getMessage(), e);
            return Result.failed("批量上传文件失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件URL
     * @return 是否删除成功
     */
    @DeleteMapping
    @Operation(summary = "删除文件", description = "根据文件URL删除MinIO中的文件")
    public Result<Boolean> deleteFile(
            @Parameter(description = "文件URL", required = true)
            @RequestParam("fileUrl") String fileUrl) {
        try {
            log.info("开始删除文件: {}", fileUrl);
            boolean result = fileService.deleteFile(fileUrl);
            if (result) {
                log.info("文件删除成功: {}", fileUrl);
                return Result.success("文件删除成功", true);
            } else {
                log.warn("文件删除失败: {}", fileUrl);
                return Result.failed("文件删除失败");
            }
        } catch (Exception e) {
            log.error("文件删除失败: {}, 错误: {}", fileUrl, e.getMessage(), e);
            return Result.failed("文件删除失败: " + e.getMessage());
        }
    }
} 